﻿using YMJF_Service.Common;
using YMJF_Service.Helpers;
using YMJF_Service.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;

namespace YMJF_Service.Controllers
{
    /// <summary>
    /// 上传处理类
    /// </summary>
    public class FileUploadController : ApiController
    {
        FilesHelper filesHelper;
        String tempPath = "~/somefiles/";
        String serverMapPath = "~/Files/somefiles/";
        private string StorageRoot
        {
            get { return Path.Combine(HostingEnvironment.MapPath(serverMapPath)); }
        }
        private string UrlBase = "/Files/somefiles/";
        String DeleteURL = "/FileUpload/DeleteFile/?file=";
        String DeleteType = "GET";
        public FileUploadController()
        {
            filesHelper = new FilesHelper(DeleteURL, DeleteType, StorageRoot, UrlBase, tempPath, serverMapPath);
        }

        public string OPTIONS()
        {
            return null;
        }

        public JsonFiles Show()
        {
            JsonFiles ListOfFiles = filesHelper.GetFileList();
            var model = new FilesViewModel()
            {
                Files = ListOfFiles.files
            };

            return ListOfFiles;
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="FileName">文件夹名称</param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult Upload(string fileName)
        {
            var content = Request.Content;
            var uploadDir = HttpContext.Current.Server.MapPath("~/Upload/" + fileName + "/");
            var newFileName = "";
            var orgFileName = "";//原始文件名称
            var sp = new MultipartMemoryStreamProvider();
            Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait();

            foreach (var item in sp.Contents)
            {
                if (item.Headers.ContentDisposition.FileName != null)
                {
                    //建立临时传输文件夹
                    if (!Directory.Exists(Path.GetDirectoryName(uploadDir)))
                    {
                        Directory.CreateDirectory(uploadDir);
                    }
                    orgFileName = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                    string ExtName = Path.GetExtension(orgFileName);

                    //上传间隔时间短，回造成名字重复
                    //var filename = DateTime.Now.ToString("yyyyMMddHHmmssffffff") + Help.GenerateRandomNumber(6) + ExtName;//yyyyMMddHHmmssffffff
                    var filename = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString() + ExtName;
                    // var filename = Guid.NewGuid().ToString() + ExtName;
                    //var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                    newFileName = uploadDir + filename;
                    var ms = item.ReadAsStreamAsync().Result;
                    using (var br = new BinaryReader(ms))
                    {
                        var data = br.ReadBytes((int)ms.Length);
                        File.WriteAllBytes(newFileName, data);
                    }
                }
            }

            ApiResult res = new ApiResult();
            res.code = HttpCode.success;
            res.message = "上传文件成功";

            var FileName = "";
            FileName = Path.GetFileName(newFileName);

            res.data = new
            {
                url = "/Upload/" + fileName + "/" + FileName,
                fileName = orgFileName,
                name = Path.GetFileNameWithoutExtension(FileName)
            };

            return res;
        }

        public JsonFiles GetFileList()
        {
            var list = filesHelper.GetFileList();
            return list;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file">文件名</param>
        /// <returns></returns>
        [HttpGet]
        public ApiResult DeleteFile(string file)
        {
            filesHelper.DeleteFile(file);

            ApiResult res = new ApiResult();
            res.code = HttpCode.success;
            res.message = "删除文件成功";

            return res;
        }
       
    }
}